package pattern;

import org.springframework.util.StopWatch;

import java.util.concurrent.TimeUnit;

public class BalkingDemo {

  static  class Singleton {

        private static volatile Singleton singleton;

        private Singleton() {}

        public static Singleton getInstance() {
            if (singleton == null) {
                synchronized (Singleton.class) {
                    System.out.println("luck got lock!");
                    if (singleton == null) {
                        singleton = new Singleton();
                    }
                }
            }
            return null;
        }
    }

    public static void main(String[] args) throws  Exception {

      StopWatch stopWatch = new StopWatch();
      Thread t1 = new Thread(
              () -> {
                  synchronized (stopWatch) {
                      doInit(stopWatch, "11111");
                  }

              }
      );

      Thread t2 = new Thread(
                () -> {
                    synchronized (stopWatch) {
                        doInit(stopWatch, "22222");
                    }
                }
      );
      t1.start();
      t2.start();
      t1.join();
      t2.join();

        System.out.println(stopWatch.prettyPrint(TimeUnit.MILLISECONDS));
    }

    private static void doInit(StopWatch stopWatch, String taskName) {
        stopWatch.start(taskName);
        Singleton.getInstance();
        stopWatch.stop();
    }


}
